﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using BL.ServerBL;
using Common.IO.FileIO;
using Common.ClassLib;

namespace SystemServer
{
    public partial class SystemServer : Form
    {

        ServerChannel SystemServerChannel;
        string IniFileName = "SystemServer.ini";
        bool IsServerOpened;
        bool CloseDirectly = false;
        public SystemServer()
        {
            InitializeComponent();
        }

        private void SystemServer_Load(object sender, EventArgs e)
        {
            this.InitDBConfig();
            this.InitServer();
            this.InitUserListen();
            
            SystemServerChannel.ServerChannelControl(true);

        }

        private void InitTaskShow()
        {
            this.NIcon.Icon = new Icon("ico\\Provider.ico");
            this.NIcon.Visible = false;
            this.ShowInTaskbar = false;

        }
        
        #region 数据库设置
        private void InitDBConfig()
        {
            ComboBoxItem[] cbilist = {new ComboBoxItem("企业版", "Enterprise"),
                new ComboBoxItem("简易版", "Express"), new ComboBoxItem("开发版","Develop")};
            this.cbDBVer.Items.Clear();
            foreach(ComboBoxItem cbi in cbilist)
            {
                
                this.cbDBVer.Items.Add(cbi);
            }

            IniFileIO inifile = new IniFileIO(this.IniFileName);
            string serverip = inifile.IniReadValue("DataBase", "DBServerIP");
            string dbver = inifile.IniReadValue("DataBase", "DBVer");
            DBConfigControl.SetDBConfig(serverip, dbver);

            cbServerIP.Text = serverip;
            for (int i = 0; i < this.cbDBVer.Items.Count; i++ )
            {
                if (((ComboBoxItem)cbDBVer.Items[i]).Value == dbver)
                    this.cbDBVer.SelectedIndex = i;
            }
        }

        private void btnSaveDBConfig_Click(object sender, EventArgs e)
        {
            string dbserverip = cbServerIP.Text;
            string dbver = ((ComboBoxItem)cbDBVer.SelectedItem).Value;
            DBConfigControl.SetDBConfig(dbserverip, dbver);
            IniFileIO inifile = new IniFileIO(this.IniFileName);
            inifile.IniWriteValue("DataBase", "DBServerIP", dbserverip);
            inifile.IniWriteValue("DataBase", "DBVer", dbver);
            MessageBox.Show("保存数据库设置成功！");
       }

        private void btnReSetDBConfig_Click(object sender, EventArgs e)
        {
            DBConfigControl.ReSetDBConfig();
            IniFileIO inifile = new IniFileIO(this.IniFileName);
            inifile.IniWriteValue("DataBase", "DBServerIP", "127.0.0.1");
            inifile.IniWriteValue("DataBase", "DBVer", "Enterprise");
            this.InitDBConfig();
        }
        #endregion

        #region 服务控制
        private void btnServerControl_Click(object sender, EventArgs e)
        {
            ChannelControl(!IsServerOpened);
        }

        private void ChannelControl(bool bl)
        {
            SystemServerChannel.ServerChannelControl(bl);
            if (bl)
            {
                btnServerControl.Text = "关闭服务器";
                lbServerState.Text = "服务器在线";
                lbServerStateLogo.ForeColor = System.Drawing.Color.Chartreuse;
                IsServerOpened = true;
                AddLog(true);
            }
            else
            {
                btnServerControl.Text = "开启服务器";
                lbServerState.Text = "服务器离线";
                lbServerStateLogo.ForeColor = System.Drawing.Color.Red;
                IsServerOpened = false;
                AddLog(false);
            }
        }



        private void InitServer()
        {
           
            IniFileIO programini = new IniFileIO(IniFileName);
            bool isautostart = (programini.IniReadValue("Server", "AutoStart") == "1");
            string port = programini.IniReadValue("Server", "Port");
            SystemServerChannel = new ServerChannel(port);
            if (!SystemServerChannel.RegisterServerChannel())
            {
                MessageBox.Show("已经启动了一个服务器，或该端口已被占用！");
                this.CloseDirectly = true;
                this.Close();
                return;
            }
            ChannelControl(isautostart);
            cbAutoServer.Checked = isautostart;

        }

        private void cbAutoServer_CheckedChanged(object sender, EventArgs e)
        {
            IniFileIO programini = new IniFileIO(IniFileName, false);
            programini.IniWriteValue("Server", "AutoStart", cbAutoServer.Checked ? "1" : "0");
        }

        #endregion

        #region 用户状态

        protected void InitUserListen()
        {
            UserState.OnUserLogin += new UserState.UserLogin(UserState_OnUserLogin);
            UserState.OnUserLogout += new UserState.UserLogout(UserState_OnUserLogout);
            UserState.OnBudgetReported += new UserState.BudgetReported(UserState_OnBudgetReported);
        }

        
        protected void UserState_OnUserLogin(string user_name, string user_ip, string user_hostname)
        {
            AddLog(user_name, user_ip, true);
            AddUserInfo(user_name, user_ip, user_hostname);
        }

        protected void UserState_OnUserLogout(string user_hostname)
        {
            string user_name = lvUserInfo.FindItemWithText(user_hostname).SubItems[0].Text.Trim();
            string user_ip = lvUserInfo.FindItemWithText(user_hostname).SubItems[1].Text.Trim();
            AddLog(user_name, user_ip, false);
            RemoteUserInfo(user_hostname);
        }
        

        protected void UserState_OnBudgetReported(string user_name)
        {
            string newlog = "用户："+ user_name + "上报预算成功。";
            AddLog(newlog);
        }

        

        protected void UserState_OnBCUserLogin(string user_name, string user_ip, string user_hostname)
        {
            AddLog(user_name, user_ip, true);
            AddUserInfo(user_name, user_ip, user_hostname);
        }

        protected void UserState_OnBCUserLogout(string user_hostname)
        {
            string user_name = lvUserInfo.FindItemWithText(user_hostname).SubItems[0].Text.Trim();
            string user_ip = lvUserInfo.FindItemWithText(user_hostname).SubItems[1].Text.Trim();
            AddLog(user_name, user_ip, false);
            RemoteUserInfo(user_hostname);
        }
        

        #endregion

        #region 日志控制
        private void AddLog(string user_name, string user_ip, bool user_state)
        {
            string newlog = DateTime.Now.ToLocalTime().ToString();
            newlog += " 用户 " + user_name;
            newlog += "  (IP:" + user_ip + ")  ";
            newlog += user_state ? "登录。" : "退出。";
            lboxLog.Items.Add(newlog);
        }

        private void AddLog(bool server_state)
        {
            string newlog = DateTime.Now.ToLocalTime().ToString();
            newlog += server_state ? " 服务器开启。" : " 服务器关闭。";
            lboxLog.Items.Add(newlog);
        }

        private void AddLog(string newlog)
        {
            newlog = DateTime.Now.ToLocalTime().ToString() + newlog;
            lboxLog.Items.Add(newlog);
        }
        #endregion

        #region 状态控制
        private void AddUserInfo(string user_name, string user_ip, string user_hostname)
        {
            string[] newitemtext = { user_name, user_ip, user_hostname, "正常登录" };
            ListViewItem newitem = new ListViewItem(newitemtext);
            lvUserInfo.Items.Add(newitem);
        }

        private void RemoteUserInfo(string user_hostname)
        {
            lvUserInfo.Items.Remove(lvUserInfo.FindItemWithText(user_hostname));
        }
        #endregion

        #region 菜单项
        private void aaaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        private void SystemServer_FormClosed(object sender, FormClosedEventArgs e)
        {
            SystemServerChannel.UnRegisterServerChannel();
        }

        private void SystemServer_MinimumSizeChanged(object sender, EventArgs e)
        {
            
        }

        private void SystemServer_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;
                this.Visible = false;
                this.NIcon.Visible = true;
            }
            
        }

        private void NIcon_Click(object sender, EventArgs e)
        {
            
        }

        private void quToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void stToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ChannelControl(false);
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ChannelControl(true);
        }

        private void SystemServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.CloseDirectly)
            {
                DialogResult dr = MessageBox.Show("确定要退出？", "确认", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No)
                    e.Cancel = true;
            }

        }

        private void NIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        

       

        

        //string[] skinfilelist = System.IO.Directory.GetFiles(@"F:\Codes\Library\Skins(.skn)\");
        //int i = 0;
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    if (i < skinfilelist.Length)
        //    {
        //        i++;
        //        skUISystemServer.SkinFile = skinfilelist[i];
        //    }
            
        //}

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    MessageBox.Show(skUISystemServer.SkinFile);
        //}

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    if (i > 0)
        //    {
        //        i--;
        //        skUISystemServer.SkinFile = skinfilelist[i];
        //    }

        //}
    }
}
